package com.jnu.myfirstapplication;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.appcompat.app.AlertDialog;

import com.google.zxing.Result;
import com.jnu.myfirstapplication.data.Book;
import com.jnu.myfirstapplication.data.Comment;
import com.jnu.myfirstapplication.data.DataSaver;
import com.jnu.myfirstapplication.data.HttpUtil;
import com.jnu.myfirstapplication.data.PicUrl;
import com.jnu.myfirstapplication.data.TitleBean;
import com.king.zxing.CaptureActivity;
import com.king.zxing.DecodeConfig;
import com.king.zxing.DecodeFormatManager;
import com.king.zxing.analyze.MultiFormatAnalyzer;

import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class QRCodeActivity extends CaptureActivity {
    private String title;

    public class ThreadB implements Runnable {

        private String result;


        public ThreadB(String result){
            this.result = result;
        }
        public void run() {
            System.out.println("线程B开始执行");
            try {
                Intent intent=getIntent();
                String control=getIntent().getStringExtra("data");
                if(control.equals("comment")){
                    Uri uri = Uri.parse("https://api.jike.xyz/situ/book/isbn/"+result+"?apikey=14368.651436e139099ed76f598dcba8f6ad98.6595ce4aea376dd1e1edf4f2d93b0173");
                    HttpUtil httpUtil=new HttpUtil();
                    String response=httpUtil.sendRequestWithOkhttp(uri.toString());
                    JSONObject jsonObject=new JSONObject(response);
                    JSONObject object =jsonObject.getJSONObject("data");
                    String douban=object.getString("douban");
//                    uri=Uri.parse("https://book.douban.com/subject/"+douban+"/comments/");
//                    String htmlContent=httpUtil.getHtmlContent("https://book.douban.com/subject/"+douban+"/comments/");
//                    System.out.println(htmlContent);
//                    startActivity(new Intent(Intent.ACTION_VIEW,uri));

//                    Uri uri = Uri.parse("https://search.douban.com/book/subject_search?search_text="+result+"&cat=1001");

//                    Document doc = Jsoup.connect("https://book.douban.com/subject/"+douban+"/comments/").timeout(5000).followRedirects(true).execute().parse();
//                    Elements elements = doc.getElementsByClass("short");//查找所有class为"title"的元素
//                    for (Element e : elements) {
//                        Elements titles = e.getElementsByTag("a");//在每一个找到的元素中，查找<a>标签
//                        for (Element title : titles) {
//                            //将找到的标签数据封装起来
//                            TitleBean bean = new TitleBean();
//                            bean.setTitle(title.text());//获取标签的内容，也就是文章标题
//                            bean.setUrl(title.attr("href"));//获取标签属性，也就是文章链接
//                            String pattern = "\\d+";
//                            // Create a Pattern object
//                            Pattern r = Pattern.compile(pattern);
//                            // Now create matcher object.
//                            Matcher m = r.matcher(title.attr("href"));
//                            if (m.find( )){
//                                comment=m.group();
//                            }
//                        }
//                    }
                    Document doc = Jsoup.connect("https://book.douban.com/subject/"+douban+"/comments/")
                            .userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31")
                            .execute().parse();
                    Elements comment = doc.getElementsByClass("short");//查找所有class为"title"的元素
                    Elements username = doc.getElementsByClass("avatar");
                    Elements time = doc.getElementsByClass("comment-time");
                    Elements frequency = doc.getElementsByClass("vote-count");
                    ArrayList<Comment> comments = new ArrayList<>();
                    for(int i = 0;i<comment.size();i++){
                        Comment comment1 = new Comment();
                        comment1.setComment(comment.get(i).text());
                        comment1.setUsername(username.get(i).childNode(1).attr("title").toString());
                        comment1.setImageUrl(username.get(i).childNode(1).childNode(1).attr("src").toString());
                        comment1.setTime(time.get(i).text());
                        comment1.setFrequency(Integer.parseInt(frequency.get(i).text()));
                        comments.add(comment1);
                    }
                    for(Comment comment1:comments){
                        System.out.print(comment1.getUsername()+"\t");
                        System.out.print(comment1.getImageUrl()+"\t");
                        System.out.print(comment1.getComment()+"\t");
                        System.out.print(comment1.getTime()+"\t");
                        System.out.print(comment1.getFrequency()+"\n");
                    }
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("comments",comments);
                    Intent intent1 = new Intent(QRCodeActivity.this, CommentPage.class);
                    intent1.putExtras(bundle);
                    startActivity(intent1);

                }else if(control.equals("value")){
                    Uri uri = Uri.parse("http://search.dangdang.com/?key="+result+"&act=input");
                    HttpUtil httpUtil = new HttpUtil();
                    String htmlContent=httpUtil.getHtmlContent("http://search.dangdang.com/?key="+result+"&act=input");
                    System.out.println(htmlContent);
                    startActivity(new Intent(Intent.ACTION_VIEW,uri));
                }else if(control.equals("information")){
                    Uri uri = Uri.parse("https://api.jike.xyz/situ/book/isbn/"+result+"?apikey=14368.651436e139099ed76f598dcba8f6ad98.6595ce4aea376dd1e1edf4f2d93b0173");
                    HttpUtil httpUtil=new HttpUtil();
                    String response=httpUtil.sendRequestWithOkhttp(uri.toString());
                    JSONObject jsonObject=new JSONObject(response);
                    JSONObject object =jsonObject.getJSONObject("data");

                    title=object.getString("name");
                    String author=object.getString("author");
                    String publisher=object.getString("publishing");
                    String notes=object.getString("subname");
                    String Translator=object.getString("translator");
                    String ISBN=result;
                    String photoUrl=object.getString("photoUrl");
                    String website="https://book.douban.com/subject/"+object.getString("douban")+"/";
                    Intent backIntent=new Intent();
                    backIntent.putExtra("title",title);
                    backIntent.putExtra("author",author);
                    backIntent.putExtra("publisher",publisher);
                    backIntent.putExtra("notes",notes);
                    backIntent.putExtra("Translator",Translator);
                    backIntent.putExtra("ISBN",ISBN);
                    backIntent.putExtra("photoUrl",photoUrl);
                    backIntent.putExtra("website",website);
                    setResult(500,backIntent);
                    finish();
//                    for(int i=0;i<jsonArray.length();i++)
//                    {
//                        JSONObject jsonObject=jsonArray.getJSONObject(i);
//                        String author=jsonObject.getString("author");
//                        String name=jsonObject.getString("name");
//                    }

                }
                else if(control.equals("batchImport")){
                    Uri uri = Uri.parse("https://api.jike.xyz/situ/book/isbn/"+result+"?apikey=14368.651436e139099ed76f598dcba8f6ad98.6595ce4aea376dd1e1edf4f2d93b0173");
                    HttpUtil httpUtil=new HttpUtil();
                    String response=httpUtil.sendRequestWithOkhttp(uri.toString());
                    JSONObject jsonObject=new JSONObject(response);
                    JSONObject object =jsonObject.getJSONObject("data");

                    title=object.getString("name");
                    String author=object.getString("author");
                    String publisher=object.getString("publishing");
                    String notes=object.getString("subname");
                    String Translator=object.getString("translator");
                    String ISBN=result;
                    String photoUrl=object.getString("photoUrl");
                    String website="https://book.douban.com/subject/"+object.getString("douban")+"/";
                    String uuid = UUID.randomUUID().toString();

                    if (photoUrl.length() > 0) {
                        //正确返回url了才保存
                        try {
                            PicUrl picUrl = new PicUrl();
                            Bitmap bitmap = picUrl.returnBitMap(photoUrl);
                            if (bitmap != null) {
                                BookListMainActivity.bookCoverNumber++;  //bookCoverNumber+1并保存
                                picUrl.saveImg(bitmap, "/sdcard/Pictures/book/", "book" + BookListMainActivity.bookCoverNumber);
                                new DataSaver().saveBookCoverNumber(getApplicationContext(), BookListMainActivity.bookCoverNumber);
//                                intent.putExtra("id", bookCoverNumber);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    Book book = new Book(title, BookListMainActivity.bookCoverNumber, author, Translator, publisher, null, ISBN, 0, 0,
                            notes, null, website,
                            BookListMainActivity.bookBookShelfHashMap.get("default").size());
                    book.setUuid(uuid);

                    AlertDialog alertDialog = new AlertDialog.Builder(QRCodeActivity.this)
                            .setTitle("确认图书")
                            .setMessage(title+"扫描结果正确吗？如果正确且想连扫请点击Yes，若扫描错误或想退出请点击No")
                            .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            }).setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {

                                }
                            }).create();
                    alertDialog.show();
                }
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("线程B出异常了");
            }
            System.out.println("线程B执行结束");
        }
        public String getBookName(){
            return title;
        }
    }



    public interface MyRunnable extends Runnable {
        public MyRunnable setParam(String param);
    }
    MyRunnable runnable2=new MyRunnable() {
        String result;
        @Override
        public MyRunnable setParam(String param) {
            result=param;
            return this;
        }

        @Override
        public void run() {
        }
    };
    MyRunnable runnable=new MyRunnable() {
        String result;
        @Override
        public MyRunnable setParam(String param) {
            result=param;
            return this;
        }

        @Override
        public void run() {
            // TODO: http request.
            String comment="";
            try {
                //获取okhttp对象
                OkHttpClient client =new OkHttpClient();
                Request request = new Request.Builder()
                        .url("https://search.douban.com/book/subject_search?search_text="+result+"&cat=1001")
                        .addHeader("application/x-www-form-urlencoded","charset=utf-8")
                        .build();

                Call call = client.newCall(request);
                //第四步 call对象调用enqueue()方法，通过Callback()回调拿到响应体Response
                call.enqueue(new Callback() {
                    @Override
                    public void onFailure(Call call, IOException e) {
                        //异步请求失败之后的回调
                    }

                    @Override
                    public void onResponse(Call call, Response response) throws IOException {
                        //异步请求成功之后的回调
                        String html=response.body().string();
                    }
                });

                //获取请求返回数据
                Response response = client.newCall(request).execute();
                //回调输入流
//                InputStream inputStream = response.body().byteStream();
                String html=response.body().string();
//                Document doc = Jsoup.connect("https://search.douban.com/book/subject_search?search_text="+result+"&cat=1001").get();//通过url获取到网页内容
                Document doc = Jsoup.connect("https://search.douban.com/book/subject_search?search_text="+result+"&cat=1001").timeout(5000).followRedirects(true).execute().parse();
                Elements elements = doc.getElementsByClass("title");//查找所有class为"title"的元素
                for (Element e : elements) {
                    Elements titles = e.getElementsByTag("a");//在每一个找到的元素中，查找<a>标签
                    for (Element title : titles) {
                        //将找到的标签数据封装起来
                        TitleBean bean = new TitleBean();
                        bean.setTitle(title.text());//获取标签的内容，也就是文章标题
                        bean.setUrl(title.attr("href"));//获取标签属性，也就是文章链接
                        String pattern = "\\d+";
                        // Create a Pattern object
                        Pattern r = Pattern.compile(pattern);
                        // Now create matcher object.
                        Matcher m = r.matcher(title.attr("href"));
                        if (m.find( )){
                            comment=m.group();
                        }
                    }
                }
                Uri uri = Uri.parse("https://book.douban.com/subject/"+comment+"/comments/");
                startActivity(new Intent(Intent.ACTION_VIEW,uri));
//            msgHandler.sendEmptyMessage(MSG_LOAD_OK);//通知UI更新List
            } catch (IOException e) {
                e.printStackTrace();
            }
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("value","请求结果");
            msg.setData(data);
            handler.sendMessage(msg);
        }
    };

    @Override
    public int getLayoutId() {
        return R.layout.activity_qrcode;
    }

    @Override
    public void initCameraScan() {
        super.initCameraScan();



        //初始化解码配置
        DecodeConfig decodeConfig = new DecodeConfig();
        decodeConfig.setHints(DecodeFormatManager.DEFAULT_HINTS)//如果只有识别二维码的需求，这样设置效率会更高，不设置默认为DecodeFormatManager.DEFAULT_HINTS
                .setFullAreaScan(false)//设置是否全区域识别，默认false
                .setAreaRectRatio(0.8f)//设置识别区域比例，默认0.8，设置的比例最终会在预览区域裁剪基于此比例的一个矩形进行扫码识别
                .setAreaRectVerticalOffset(0)//设置识别区域垂直方向偏移量，默认为0，为0表示居中，可以为负数
                .setAreaRectHorizontalOffset(0);//设置识别区域水平方向偏移量，默认为0，为0表示居中，可以为负数

        //在启动预览之前，设置分析器，只识别二维码
        getCameraScan()
                .setVibrate(true)//设置是否震动，默认为false
                .setNeedAutoZoom(true)//二维码太小时可自动缩放，默认为false
                .setAnalyzer(new MultiFormatAnalyzer(decodeConfig));//设置分析器,如果内置实现的一些分析器不满足您的需求，你也可以自定义去实现
    }


    /*
     * 扫码结果回调
     * @param result
     * @return 返回false表示不拦截，将关闭扫码界面并将结果返回给调用界面；
     *  返回true表示拦截，需自己处理逻辑。当isAnalyze为true时，默认会继续分析图像（也就是连扫）。
     *  如果只是想拦截扫码结果回调，并不想继续分析图像（不想连扫），请在拦截扫码逻辑处通过调
     *  用{@link CameraScan#setAnalyzeImage(boolean)}，
     *  因为{@link CameraScan#setAnalyzeImage(boolean)}方法能动态控制是否继续分析图像。
     *
     */
    @Override
    public boolean onScanResultCallback(Result result) {
        /*
         * 因为setAnalyzeImage方法能动态控制是否继续分析图像。
         *
         * 1. 因为分析图像默认为true，如果想支持连扫，返回true即可。
         * 当连扫的处理逻辑比较复杂时，请在处理逻辑前调用getCameraScan().setAnalyzeImage(false)，
         * 来停止分析图像，等逻辑处理完后再调用getCameraScan().setAnalyzeImage(true)来继续分析图像。
         *
         * 2. 如果只是想拦截扫码结果回调自己处理逻辑，但并不想继续分析图像（即不想连扫），可通过
         * 调用getCameraScan().setAnalyzeImage(false)来停止分析图像。
         */


//        try{
//            Thread t1=new Thread(runnable2.setParam(result.getText()));
//            t1.start();
//            t1.join();
//        }catch (Exception e){
//            e.printStackTrace();
//        }

//        try{
//            Thread.sleep(2000);
//        }catch (Exception e){
//            e.printStackTrace();
//        }

//        Intent intent=getIntent();
//        String control=getIntent().getStringExtra("data");
//        if(control.equals("comment")){
//            Uri uri = Uri.parse("https://search.douban.com/book/subject_search?search_text="+result+"&cat=1001");
//            startActivity(new Intent(Intent.ACTION_VIEW,uri));
//        }else if(control.equals("value")){
//            Uri uri = Uri.parse("http://search.dangdang.com/?key="+result+"&act=input");
//            startActivity(new Intent(Intent.ACTION_VIEW,uri));
//        }else if(control.equals("information")){
//            Uri uri = Uri.parse("https://api.jike.xyz/situ/book/isbn/"+result+"?apikey=14368.651436e139099ed76f598dcba8f6ad98.6595ce4aea376dd1e1edf4f2d93b0173");
//            HttpUtil httpUtil=new HttpUtil();
//            httpUtil.sendRequestWithOkhttp(uri.toString(), new okhttp3.Callback() {
//                @Override
//                public void onFailure(Call call, IOException e) {
//
//                }
//
//                @Override
//                public void onResponse(Call call, Response response) throws IOException {
//                    parseJsonWithJsonObject(response);
//                }
//            });
//        }



//        Uri uri = Uri.parse("https://book.douban.com/subject/"+comment+"/comments/");
//        startActivity(new Intent(Intent.ACTION_VIEW,uri));

        //应该要设置一个线程一直扫描是否获取到result了，不然直接开始子进程就莫名卡死了
        //直接运行就可以正常获得，debug却不行？
        Thread threadB = new Thread(new ThreadB(result.getText()));
        threadB.start();
        try {
            threadB.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主线程执行完毕");

//        AlertDialog
//        return true;
        System.out.println(title);
        return super.onScanResultCallback(result);
//        getCameraScan().setAnalyzeImage(false);

    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("value");
            Log.i("TAG","请求结果:" + val);
        }
    };

    public static String parseResponse(InputStream inputStream) {

        try {
            //输入流转文本
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "GBK"));
            StringBuilder response = new StringBuilder();
            String line = reader.readLine();
            while (line != null) {
                response.append(line);
                line = reader.readLine();
            }
            //获取html数据
            String html = response.toString();
            return html;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }
}